<template>
	<section>
		<!--高级查询 +工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form  :inline="true">
				<el-form-item>
					<el-input v-model="keyword" placeholder="关键字" ></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="warning" v-on:click="keywordQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="addHandler">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>


    <!--列表v-loading="listLoading"-->
    <el-table border :data="tableDatas" v-loading="listLoading" @selection-change="handleSelectionChange"
              highlight-current-row :row-key="getKey" ref="multable"  style="width: 100%;">
      <!--多选框-->
      <el-table-column type="selection"  width="55"reserve-selection >
      </el-table-column>
      <el-table-column type="index" width="70" label="序号" fixed="left">
      </el-table-column>
      <el-table-column prop="articlePic" label="文章封面" :show-overflow-tooltip="true" width="280" fixed="left">
      </el-table-column>
      <el-table-column prop="articleName" label="文章名称" :show-overflow-tooltip="true" width="200" fixed="left">
      </el-table-column>
      <el-table-column prop="articleTypes.typeName" label="所属分类" :show-overflow-tooltip="true" width="160">
      </el-table-column>
      <el-table-column prop="articleTag" label="文章标签" :show-overflow-tooltip="true" width="200">
      </el-table-column>
      <el-table-column prop="users.userName" label="作者" width="110">
      </el-table-column>

      <el-table-column prop="articleState"  label="文章状态" width="100">
        <template scope="scope">
          <span v-if="scope.row.articleState==0"  style="color: blueviolet ">草稿</span>
          <span v-if="scope.row.articleState==1"  style="color: #11b95c ">发布</span>
          <span v-if="scope.row.articleState==-1"   style="color: darkorange">弃用</span>
        </template>
      </el-table-column>
      <el-table-column prop="articleReadCount" label="阅读量" width="110">
      </el-table-column>
      <el-table-column prop="articleStarNum" label="点赞量" width="110">
      </el-table-column>
      <el-table-column prop="articleCommentNum" label="评论数" width="110">
      </el-table-column>

      <el-table-column prop="topState" label="是否置顶" width="100" >
        <!--是否置顶(0:不置顶;1:置顶)-->
        <template scope="scope" >
          <span v-if="scope.row.articleState==0"  style="color: #13ce66">不置顶</span>
          <span v-if="scope.row.articleState==1"  style="color: red">置顶</span>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="最后修改时间" width="170" sortable>
      </el-table-column>
      <el-table-column label="操作" align="center" width="170" fixed="right">
        <template scope="scope">
          <el-button size="small"  @click="edit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="del(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

		<!-- 分页的大学   工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" :disabled="this.sels.length===0" @click="delBatch">批量删除</el-button>
			<el-pagination
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="currentPage"
					:page-sizes="[5, 10]"
					:page-size="pageSize"
          :total="totals"
					layout="total, sizes, prev, pager, next, jumper"
          background
					style="float:right;">
			</el-pagination>
		</el-col>

    <!--
      :model="saveForm"  - 表单绑定模型数据对象saveForm
      label-width="80px"  - 标签的宽度
      :rules="saveFormRules" - 验证规则 - 表单项校验
      ref="saveForm" - 为当前对话框取名saveForm - 做表单校验

      label="姓名" - 标签名字
      prop="name" - 要做校验的时候必须要，不做校验就没有必要
      v-model="saveForm.name" - 双向绑定
      auto-complete="off" - 自动完成 - 关闭
    -->
    <!--新增界面-->
    <el-dialog title="新增文章" :visible.sync="saveFormVisible"  :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px"  :rules="saveFormRules" ref="saveForm">
        <!--文件上传-->
        <el-form-item label="文章封面">
          <el-upload class="upload-demo"
                     action="http://localhost:8080/minio"
                     name="file"
                     :on-remove="handleRemove"
                     :on-success="handleSuccess"
                     :on-exceed="exceed"
                     :file-list="fileList"
                     :limit=1
                     accept=".jpg,.jpeg,.png,.gif"
                     list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip" style=" color: red">只能上传指定类型的图片 </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章类型" prop="articleType">
          <el-select v-model="saveForm.articleType" placeholder="请选择文章类型">
            <el-option v-for ="item in articleTypes"
                      :label="item.typeName"
                      :value="item.id">
              <span style="float: left">{{ item.typeName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章作者" prop="userId">
          <el-select v-model="saveForm.userId" placeholder="请选择文章作者">
            <el-option v-for ="item in users"
                       :label="item.userName"
                       :value="item.id">
              <span style="float: left">{{ item.userName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章名称" prop="articleName">
          <el-input v-model="saveForm.articleName" placeholder="请输入文章名称" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="文章标签" prop="articleTag">
          <el-input v-model="saveForm.articleTag" placeholder="请输入文章标签" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="文章状态" prop="articleState">
          <el-radio-group v-model="saveForm.articleState">
            <el-radio :label="0"border  >草稿</el-radio>
            <el-radio :label="1"border >发布</el-radio>
            <el-radio :label="-1"border >弃用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否置顶" prop="topState">
          <el-radio-group v-model="saveForm.topState">
            <el-radio :label="0"border >不置顶</el-radio>
            <el-radio :label="1"border >置顶</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="文章简介" prop="articleRemark">
          <div class="edit_container">
            <quill-editor v-model="saveForm.articleRemark"
                          :options="editorOption"
                          @ready="onEditorReady($event)">
            </quill-editor>
          </div>
        </el-form-item>

        <el-form-item label="文章内容" prop="articleContent">
          <div class="edit_container">
            <quill-editor v-model="saveForm.articleContent"
                          :options="editorOption"
                          @ready="onEditorReady($event)">
            </quill-editor>
          </div>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" >提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
//引入Vue的ueditor的资源
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
// 工具栏配置
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  ["blockquote", "code-block"], // 引用  代码块-----['blockquote', 'code-block']
  [{header: 1}, {header: 2}], // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
  [{list: "ordered"}, {list: "bullet"}], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  [{script: "sub"}, {script: "super"}], // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
  [{indent: "-1"}, {indent: "+1"}], // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
  [{direction: "rtl"}], // 文本方向-----[{'direction': 'rtl'}]
  [{size: ["small", false, "large", "huge"]}], // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
  [{header: [1, 2, 3, 4, 5, 6, false]}], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
  [{color: []}, {background: []}], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
  [{font: []}], // 字体种类-----[{ font: [] }]
  [{align: []}], // 对齐方式-----[{ align: [] }]
  ["clean"], // 清除文本格式-----['clean']
  ["image", "link"] // 链接、图片、视频-----['link', 'image', 'video']
];


export default {
  //调用编辑器
  components: {
    quillEditor
  },

		data() {
			return {
			  //1.分页的数据
        tableDatas:[], //当前页数据
        listLoading:false,
        currentPage:1,//当前页
        pageSize:5,//每页显示的条数
        totals:0,//总条数

        //2.高级查询
        keyword:'',

        //3.当前行的数据   取id
        row:"",

        //4.批量删除选择
				sels: [], //存储多选记录

        //查询文章类型
        articleTypes:{},
        //查询用户
        users:{},

        //5.新增修改的对话框
        saveFormVisible:false,
        title:'',
				saveForm:{
          id:null,
          articlePic:'',
          articleName:'',
          articleTag:'',
          articleRemark:'',
          articleState:null,
          articleContent:'',
          articleType:null,
          topState:null,
          userId:null,
				},

        //6.富文本编辑器配置
        editorOption: {
          modules: {
            //工具栏定义的
            toolbar: toolbarOptions
          },
          //主题
          theme: "snow",
          placeholder: "请开始书写您的博客内容..."
        },
        //7.上传的文件列表
        fileList: [],//上传的文件列表
        imgPrefix: "http://115.159.88.63:9090/java1125-test/",

        //表单项验证
        saveFormRules: {
          articleType: [
            {required: true, message: '请选择文章类型', trigger: 'blur'}
          ],
          articleName: [
            {required: true, message: '请输入文章名称', trigger: 'blur'}
          ],
          articleTag: [
            {required: true, message: '请输入文章标签', trigger: 'blur'}
          ],
          userId: [
            {required: true, message: '请选择文章作者', trigger: 'blur'}
          ],
          articleState: [
            {required: true, message: '请选择文章状态', trigger: 'blur'}
          ],
          topState: [
            {required: true, message: '请选择是否置顶', trigger: 'blur'}
          ]
        },

			}
		},
		methods: {
      getKey(row){//跨页删除
        return row.id;},

      //高级查询----第几页时触发
      keywordQuery() {
        this.currentPage=1;//重置第一页
        this.getTableData();
      },
      //选择第几页时触发
      handleCurrentChange(curentPage) {
        this.currentPage = curentPage;
        this.getTableData();
        this.handleSelectionChange();
      },
      //选择每页显示记录条数
      handleSizeChange(pageSize) {
        this.pageSize = pageSize;
        this.getTableData();
        this.handleSelectionChange();
      },

    //----------------------------------------------
      //1.获取列表数据
      getTableData(){
        let para = {
          "currentPage": this.currentPage,
          "pageSize": this.pageSize,
          "keyword":this.keyword
        };
        this.listLoading = true; //显示加载圈
        //分页查询
        this.$http.post("/article", para).then(result=>{
          this.totals = result.data.total;//总条数
          this.tableDatas = result.data.list;//模型数据赋值
          this.listLoading = false;  //关闭加载圈

        });
      },

      //2.删除单条数据
      del(row){
        this.$confirm('确定删除此条数据吗？', '请确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.delete("/article/" + row.id).then(result=>{
            if(result.data.success){
              this.$message.success("删除成功");//成功
              //------------------------------------------------------------------
              //删除成功之后对当前页的处理【特殊情况：删除最后一页的最后一条数据】
              var totalPage = Math.ceil(this.totals/this.pageSize); //总页数 = 最后一页
              //如果当前页是最后一页                  并且是最后一条数据                  并且不是第一页
              if(this.currentPage==totalPage && (this.totals-1)%this.pageSize==0 && this.currentPage!=1){
                this.currentPage--;
              }

              this.getTableData();
            }else{
              this.$message.error("系统繁忙【500】");
            }
          }).catch(res=>{
            this.$message.error("系统繁忙【400,404】");
          });
        }).catch(() => {
          this.$message.info("已取消操作")
        });
      },

      //3.表格多条数据选中事件
      handleSelectionChange(val) {
        /**
         * val中存放的是所有已选择的行数据集合
         */
        this.sels = val.map(res => res.id);
        console.log(this.sels)
      },


      //3.批量删除
      delBatch(){
        this.$confirm('确定删除这些数据吗？', '请确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.patch("/article", this.sels).then(result=>{
            if(result.data.success){
              //答应后端的成功信息
              this.$message.success(result.data.message);//成功
              this.currentPage=1;//重置第一页
              this.getTableData();
            }else{
              this.$message.error("系统繁忙【500】");
            }
          }).catch(res=>{
            this.$message.error("系统繁忙【400,404】");
          });
        }).catch(() => {
          this.$message.info("已取消操作")
        });
        //this.$refs.multable.clearSelection();
      },

      //4.添加数据
      addHandler(){
        this.title="新增";
        this.saveForm = {
          id:null,
          articlePic:'',
          articleName:'',
          articleTag:'',
          articleRemark:'',
          articleState:0,
          articleContent:'',
          articleType:null,
          topState:0,
          userId:null,
        };
        //查询文章类型
        this.getArticleType();//下拉选
        //查询登录用户
        this.getUsers();//下拉选

        this.fileList=[];//添加是把文件制空
        this.saveFormVisible = true;//显示对话框
      },
      //4.点击编辑 ---修改
      edit(row){
        this.title="修改";
        this.saveFormVisible = true;//显示编辑
        this.saveForm = Object.assign({}, row);//回显数据
        //查询文章类型
        this.getArticleType();//下拉选
        //查询登录用户
        this.getUsers();//下拉选

        //文件上传的回显删除
        this.fileList=[];
        if (row.articlePic){
          this.fileList.push({"url":row.articlePic});
        }
      },

			//6.提交新增表单数据
      saveSubmit(){
        this.$http.put("/article", this.saveForm).then(result=>{
          this.saveFormVisible = false;
					if(result.data.success){
            //答应后端的成功信息
            this.$message.success(result.data.message);//成功
            this.getTableData();
          }else{
           // this.$message.error("系统繁忙【500】");
            //打印后端的错误信息
            this.$message.error(result.data.message);
          }

				}).catch(res=> {
          this.$message.error("系统繁忙【400,404】");
        });
			},
      //查询文章类型
      getArticleType() {
        this.$http.get("/articleType").then(res => {
          if (res) {
            this.articleTypes = res.data
          }
        })
      },

      //查询文章类型
      getUsers() {
        this.$http.get("/user").then(res => {
          if (res) {
            this.users = res.data
          }
        })
      },

      onEditorReady(editor) {
        //当富文本编辑框初始化好执行
        console.log('富文本编辑框初始化---------完成');
      },

      //8.文件超出个数限制时的钩子
      exceed(files, fileList){
        this.$message({
          message: "最多只能上传一张封面照哦",
          type: 'error'
        });
      },

      //8.文件上传的业务逻辑
      handleSuccess(response, file, fileList){
        this.saveForm.articlePic = this.imgPrefix + response.resultObj;
      },
      //8.文件删除的业务逻辑
      handleRemove(file, fileList) {
        var fileName = null;
        if(file.response){ //删除刚上传的图片
          fileName = file.response.resultObj;
        }else{//删除回显的图片
          fileName = file.url.substring(file.url.lastIndexOf("/")+1);
        }
        this.$http.delete("/minio/"+fileName).then(res=>{
          if(res.data.success){
            this.$message.success('删除成功');
            //文件删除了 也要制空 表单的文件
            this.fileList=[];
            this.saveForm.articlePic="";
          }else{
            this.$message.error('删除失败');
          }
        })
      },



		},
		mounted() {

		    this.getTableData();

		}
	}

</script>

<style scoped>

</style>
